package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.SetMealDao;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 检查项服务
 */
@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outputpath;//从属性文件中读取要生成的html对应的目录

    //添加体检套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增检查组
        setMealDao.add(setmeal);
        //设置套餐和检查组关联
        Integer setmealId = setmeal.getId();
        setSetMealAndCheckGroup(setmealId, checkgroupIds);
        //将图片保存到redis集合中
        String filename = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, filename);

        //当添加套餐后需要重新生成静态页面(套餐列表页面,套餐详情页面)
        generateMobileStaticHtml();

    }

    //生成当前方法所需要的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List <Setmeal> list = setMealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);

    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List <Setmeal> list){

        Map map = new HashMap();
        map.put("setmealList", list);
        generteHtml("mobil_setmeal.ftl", "m_setmeal.html", map);

    }

    //生成套餐详情静态页面(搞不好有多个)
    public void generateMobileSetmealDetailHtml(List <Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setMealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }

    }


    //用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获取配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);//获取模板对象
            //构造输出流
            out = new FileWriter(new File(outputpath + "/" + htmlPageName));
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);

        Page <Setmeal> page = setMealDao.selectByCondition(queryString);
        long total = page.getTotal();
        List <Setmeal> result = page.getResult();


        return new PageResult(total, result);
    }

    //根据id查询套餐信息
    @Override
    public Setmeal findBySetMealId(Integer setMealId) {
        return setMealDao.findBySetMealId(setMealId);
    }

    //编辑回显检查组数据
    @Override
    public List <Integer> findCheckGroupIdBysetMealId(Integer setMealId) {
        List <Integer> list = setMealDao.findCheckGroupIdBysetMealId(setMealId);
        return list;
    }

    //编辑套餐数据
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //编辑修改数据
        setMealDao.edit(setmeal);
        //根据套餐id查询关联检查组id;
        setMealDao.deleteAssoication(setmeal.getId());
        //然后添加关系别绑定
        Integer setmealId = setmeal.getId();

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map <String, Integer> map = new HashMap <>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setMealDao.setCheckGroupAndSetMeal(map);
            }

        }
    }


    //建立检查组和检查项多对多关系(抽取代码)
    public void setSetMealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map <String, Integer> map = new HashMap <>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
    }


    //modile端查询所有
    public List <Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setMealDao.findById(id);
    }


}
